package cn.com.yang;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * TODO
 * @author yangyijin
 * @since 2024年5月9日-下午5:00:34
 */
public class DecryptPhone {
	final static String WEAPP_WATERMARK = "watermark";
	final static String WEAPP_APPID = "appid";
	public static void main(String[] args) throws IOException {
		String encryptedData = "FCi3b+JShm5CoDhx8f7zOV0iAwADki4UWIpuxfpnQ7JVD5bS9pBRIP0Jhb8rrXDZMZ0L0Sgxb7HGPmpdOpGzth8Lz7G1cjO3V/rel69+uoxlRNNCrk5O0i5+OcknjyAd21iEcTN8gHZdRfEKm7X8jhmIp312YcshIXqnxymaBldQpNrzATzAGp7fgDqOBoLeg3rsI4oGrHVXafHWCHeLzQ==";
		String iv = "hU+MyxaC/3a9gL/4YQp5bw==";
		String sessionKey = "U3A96VSq1cOakXpPasdcdA==";
		
		byte[] encryptedByte= Base64.getDecoder().decode(encryptedData);
        byte[] sessionKeyByte= Base64.getDecoder().decode(sessionKey);
        byte[] ivByte=Base64.getDecoder().decode(iv);
        SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyByte, "AES");
        Cipher cipher=null;
		try {
			cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivByte);
        try {
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
        byte[] original=null;
		try {
			original = cipher.doFinal(encryptedByte);
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
        String decryptdata = new String(original);
        JSONObject jsonObject = JSONObject.parseObject(decryptdata);
        //校验数据水印和appid
        if (!jsonObject.getJSONObject(WEAPP_WATERMARK).get(WEAPP_APPID).toString().equals("wxda3073d86a3e2d45")){
        	System.out.println("crypt.errcode:decrypt data Illegal");
        }
	}

}
